import { useStore } from 'vuex'
import { Toast } from '@/utils/utils';
import { GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
// 本地环境
const NODE_ENV = process.env.NODE_ENV;
const env = NODE_ENV == 'development' ? 'test' : 'prod';
const store = useStore();
/** 导出默认域名-请求基地址 */
export const baseURL = {
  prod: 'https://cqxzx.com/api/wx_applet',
  test: 'https://test.cqxzx.com/api/wx_applet',
}[env];

console.log('当前域名:', baseURL);

// 拦截器配置
const httpInterceptor = {
  // 拦截前触发
  invoke(options) {
    // 1. 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url;
    }
    // 2. 请求超时
    options.timeout = 10000;
    // 3. 添加小程序端请求头标识
    options.header = {
      'content-type': 'application/json;charset=utf-8',
      ...options.header
    };
    // 4. 添加 token 请求头标识
    const token = GET_TOKEN();
    if (token) {
      options.header.utk = token;
    }
  }
};

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor);
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor);
export const http = {
  get: (url, data, header) => request({ method: 'GET', url, data, header }),
  post: (url, data) => request({ method: 'POST', url, data }),
  put: (url, data) => request({ method: 'PUT', url, data }),
  delete: (url, data) => request({ method: 'DELETE', url, data })
};

const request = (options) => {
  return new Promise((resolve, reject) => {
    const { header = {} } = options
    const { silent } = header
    uni.request({
      ...options,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (res.data.code == 401) {
            // store.commit('user/setUserInfo', {})
            // store.commit('user/setToken', '')
            uni.$emit('need_login')
            REMOVE_TOKEN()
            reject(res);
            setTimeout(() => {
              // !silent && Toast('请登录');
            });
          } else if (res.data.code == 200) {
            resolve(res.data.data);
          } else {
            if(!silent){
              uni.showToast({
                icon: 'none',
                title: res.data.message || '请求错误'
              });
            }
            reject(res.data);
          }
        } else if (res.statusCode === 401) {
          // store.commit('user/setUserInfo', {})
          // store.commit('user/setToken', '')
          REMOVE_TOKEN()
          uni.$emit('need_login')
          reject(res);
          setTimeout(() => {
            // !silent &&  Toast('请登录');
          });
        } else {
          if(!silent){
            uni.showToast({
              icon: 'none',
              title: res.data.message || '请求错误'
            });
          }
          reject(res);
        }
      },
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误'
        });
        reject(err);
      }
    });
  });
};
